package com.csea.lock.service;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Csea
 * @title
 * @date 2020/7/15 15:18
 */
@Service
@Slf4j
public class JmService {

    static Map<String, Integer> productMap = new HashMap<>(10);
    static Map<String, Integer> stockMap = new HashMap<>(10);
    static Map<String, String> orderMap = new HashMap<>();

    static {
        productMap.put("123456", 100000);
        stockMap.put("123456", 100000);
    }

    private String queryMap(String projectId) {
        return "商品限量：" + productMap.get(projectId) +
                "还剩下：" + stockMap.get(projectId) + " 份" +
                "下单用户数数量：" + orderMap.size();
    }

    public String querySecKillProductInfo(String projectId) {
        return this.queryMap(projectId);
    }


    @Autowired
    private RedissonClient redissonClient;

    public void secKillProject(String productId) {
        RLock lock = redissonClient.getLock("myLock");

        log.info("锁状态：{}", lock.isLocked());
        try {
            if (lock.isLocked()) {
                throw new RuntimeException("当前请求过多");
            }
            // 加锁
            lock.lock();

            // 如果库存为0 活动结束
            int stockNum = stockMap.get(productId);
            if (stockNum == 0) {
                throw new RuntimeException("商品已售空，活动结束");
            } else {
                // 模拟订单
                orderMap.put(String.valueOf(System.currentTimeMillis()), productId);
                // 扣库存
                stockNum -= 1;

                stockMap.put(productId, stockNum);
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
        } finally {
            // 解锁
            lock.unlock();
        }
    }
}
